/**
 * 简易Grid
 */
(function ($) {

    $.canui('canGrid', {
        options: {
            colModel: [],
            showPager: false,
            url: '',
            params: {},
            key: null,//主键字段名称
            data: null,
            subGrid: null,
            height: null,
            showLoadMask: false,
            elementLoadMask: null,
            oddClass: 'tr-stripe',
            autoLoad: false
        },
        _create: function () {
            var _t = this;
            if (_t.options.height) {
                _t.contentCon = _t.element.wrap('<div class="canGrid"><div style="overflow-y: auto;overflow-x: hidden;"></div></div>');
            } else {
                _t.contentCon = _t.element.wrap('<div class="canGrid"><div></div></div>');
            }


            _t.element.css('table-layout', 'fixed');

            //生成题头
            var headCon = $('<div></div>').insertBefore(_t.element.parent());
            if (_t.options.height) {//如果设置了高度
                _t.element.parent().height(_t.options.height);
            }
            _t.headTable = $('<table width="100%" style="table-layout: fixed;">').appendTo(headCon);
            _t.headTable.addClass(_t.element.attr('class') || '');
            var headTr = $('<thead><tr></tr></thead>').appendTo(_t.headTable).find('>tr');
            if (_t.options.subGrid) {
                headTr.append('<th width="2%">&#160;</th>');

                _t.element.on('click', '.icon-add', function () {

                    var $add = $(this);
                    var $currentTr = $add.closest('tr');
                    if ($add.hasClass('icon-minus')) {
                        $currentTr.next('.subGrid').hide();
                    } else {
                        if ($add.data('data-init') !== true) {//是否初始化
                            $add.data('data-init', true);
                            var $tr = $('<tr class="subGrid"><td colspan="' + _t.headTable.find('tr:first th').length + '" align="center"><div class="inner-wrap"></div></td></tr>').insertAfter($add.closest('tr'));
                            _t._createSubGridHead($tr.find('div'));
                            if (_t.options.subGrid.url) {
                                var params = _t.options.subGrid.getParams ? _t.options.subGrid.getParams($currentTr.data('rowData')) : {};
                                $.ajaxExt({
                                    url: _t.options.subGrid.url,
                                    data: params,
                                    success: function (data) {
                                        _t._createSubGridData(data, $tr.find('.inner-wrap'));
                                    }
                                })
                            }
                        }
                        $currentTr.next('.subGrid').show();
                    }

                    $(this).toggleClass('icon-minus');
                })
            }
            $.each(_t.options.colModel, function (index, col) {
                if (!col.hidden) {
                    headTr.append('<th width="{0}">{1}</th>'.format(col.width || '', col.label));
                }
            });

            if (_t.options.clickEvents) {//给元素绑定单击事件
                _t.element.on('click', function (e) {
                    var target = e.srcElement || e.target;
                    var eventId = $(target).attr('data-eventid');
                    if (eventId) {
                        _t.options.clickEvents[eventId].call(target, $(target).closest('tr').data('rowData'));
                    }
                });
            }
        },
        /**
         * 创建subGrid的题头
         * @param $target 创建的题头要插入的目标位置
         * @private
         */
        _createSubGridHead: function ($target) {
            var _t = this;

            var $table = $('<table width="100%" border="0" cellspacing="0" cellpadding="0" class="inner-table" align="center" width="97%">');
            var $tr = $('<tr>').appendTo($table);
            $.each(_t.options.subGrid.colModel, function (index, col) {
                if (!col.hidden) {
                    $tr.append('<th width="{0}">{1}</th>'.format(col.width || '', col.label));
                }
            });
            $table.appendTo($target);
        },
        /**
         * 创建subGrid的数据行
         * @param data
         * @param $target
         * @private
         */
        _createSubGridData: function (data, $target) {
            var _t = this;
            if (data) {
                var $headTh = $target.find('tr:first th');
                var $table = $('<table width="100%" class="inner-table">').appendTo($target);

                var $tr = $('<tr class="firstRow"></tr>').appendTo($table);
                $headTh.each(function (index, td) {
                    $tr.append('<td style="width: {0}px;height:0;"></td>'.format($(td).width()));
                });


                var colModel = _t.options.subGrid.colModel;
                $.each(data, function (index, item) {
                    var $newTr = $('<tr></tr>');
                    $.each(colModel, function (index, col) {
                        var $td;
                        if (col.hidden) {
                            return;
                        }
                        if (col.formatter) {
                            $td = $('<td>{0}</td>'.format(col.formatter.apply(_t.element, [item, item[col.name], rowData])));

                        } else {
                            $td = $('<td>{0}</td>'.format(item[col.name] == undefined ? '' : item[col.name]));
                        }
                        $newTr.append($td);

                    });
                    $newTr.appendTo($table);
                });
            }
        },
        _init: function () {
            var _t = this;
            if (_t.options.autoLoad) {
                _t._reqData();
            }
            if (_t.options.data) {
                _t._appendNode(_t.options.data);
            }
        },
        //请求数据
        _reqData: function () {
            var _t = this;
            var mask = null;
            if(_t.options.elementLoadMask){
            	mask = $.createMask();
            }
            
            $.ajaxExt({
                url: _t.options.url,
                data: _t.options.params,
                loadMask: _t.options.showLoadMask && {target: _t.element.parent()},
                success: function (data) {
                	if(mask){
                		mask.remove();
                	}
                    if (_t.options.showPager) {

                    } else {
                        _t._appendNode(data);
                    }
                }
            })
        },
        /**
         * 根据Data向目标table添加HTML元素
         * @param data
         * @private
         */
        _appendNode: function (data) {
            var _t = this;
            var $table = _t.element.empty();
            var $tbody = $('<tbody></tbody>');
            var $tds = _t.headTable.find('tr:first th');
            var $tr = $('<tr class="firstRow"></tr>').appendTo($tbody);
            //var isHide = _t.headTable.height() === 0;//判断表格是否是隐藏状态

            $tds.each(function (index, td) {
                $tr.append('<td width="{0}" style="height:0;"></td>'.format($(td).attr('width')));
            });
            if ($.isArray(data)) {

                $.each(data, function (index, rowData) {
                    $tbody.append(appendTr(rowData, index));
                });

            }

            $table.append($tbody);

            function appendTr(rowData, rowIndex) {
                var $tr = $('<tr></tr>');
                if (_t.options.oddClass && rowIndex % 2 === 1) {
                    $tr.addClass(_t.options.oddClass);
                }
                $tr.data('rowData', rowData);

                if (_t.options.subGrid) {
                    $tr.append('<td><a class="icon-add"></a></td>');
                }

                var $td;
                $.each(_t.options.colModel, function (index, col) {
                    if (col.hidden) {
                        return;
                    }
                    if (col.rowNum) {
                        $td = $('<td>' + (rowIndex + 1) + '</td>');
                    } else {
                        if (col.formatter) {
                            $td = $('<td>{0}</td>'.format(col.formatter.apply(_t.element, [rowIndex, rowData[col.name], rowData])));

                        } else {
                            $td = $('<td>{0}</td>'.format(rowData[col.name] == undefined ? '' : rowData[col.name]));
                        }
                    }
                    $tr.append($td);

                });
                return $tr;
            }
        },
        //重新加载
        reload: function (op) {
            var _t = this;
            $.extend(_t.options, op || {});
            _t._reqData();
        },
        /**
         * 加载外部数据
         * @param data
         */
        loadData: function (data) {
            this._appendNode(data);
        }
    });
})(jQuery);